
var Users = (function($){

	function handleGridUser() {

		var boolRender = function(v, r, i) {
			var color = v == '1' ? 'text-success' : 'text-danger';
			return '<i class="icon-circle '+color+'"></i>';
		};

		$('#grid1').datagrid({
			url: siteURL('users/load_users'),
			height: 320,
			rownumbers: true,
			pagination: true,
			pagePosition: 'top',
			autoRowHeight: false,
			checkbox: true,
			singleSelect: true,
			columns: [[
				{field: 'ck', checkbox: true},
				{field: 'username', title: 'Username', width: 150, sortable: true},
				{field: 'fullname', title: 'Fullname', width: 150, sortable: true},
				{field: 'email', title: 'Email', width: 200, sortable: true},
				{field: 'group_name', title: 'Member of', width: 150, sortable: true},
				{field: 'active', title: 'Active', width: 80, align: 'center', formatter: boolRender}
			]]
		});

		var pager = $('#grid1').datagrid('getPager');
		pager.pagination({
			buttons: [
				{text: '<i class="icon-plus"></i> Add',  handler: addUser},
				{text: '<i class="icon-pencil"></i> Edit', handler: editUser},
				{text: '<i class="icon-trash"></i> Delete', handler: deleteUser}
			]
		});

	}

	function handleWinUser() {

		// extend validation
		$.extend($.fn.validatebox.defaults.rules, {
			equal: {
				validator: function(v, p) {
					var p1 = $('[name='+p[0]+']').val();
					if (p1 && p1 !== v) {
						return false;
					}
					return true;
				},
				message: 'Password doesn\'t match'
			}
		});

		$('#winuser').show();
		$('#winuser').dialog({
			modal: true,
			width: 400,
			title: 'User Editor',
			buttons: [
				{
					text: 'Submit',
					handler: function() {
						$('#formuser').form('submit', {
							url: siteURL('users/save_user'),
							success: function() {
								$('#winuser').dialog('close');
								$('#grid1').datagrid('reload');
							}
						});
					}
				},
				{
					text: 'Close',
					handler: function() {
						$('#winuser').dialog('close');
					}
				}
			]
		});
		$('#winuser').dialog('close');

		$('form').submit(function(e){
			e.preventDefault();
		});

		// validation
		$('[name="pass2"]').validatebox({validType: "equal['pass1']"});
		$('[name="fullname"]').validatebox({required: true});
		$('[name="email"]').validatebox({
			required: true,
			validType: 'email'
		});

	}

	function addUser() {
		$('#winuser').dialog('open');
		$('#formuser').form('clear').form('reset');
	}

	function editUser() {
		var record = $('#grid1').datagrid('getSelected');
		if ( ! record) {
			$.messager.alert('Warning', 'No record selected', 'warning');
			return;
		}

		$('#winuser').dialog('open');
		$('#formuser').form('load', record);
	}

	function deleteUser() {
		var record = $('#grid1').datagrid('getSelected');
		if ( ! record) {
			$.messager.alert('Warning', 'No record selected', 'warning');
			return;
		}

		$.messager.confirm('Confirm', 'Delete selected record?', function(r){
			if (r) {
				$.ajax({
					url: siteURL('users/delete_user'),
					type: 'post',
					dataType: 'json',
					data: record
				})
				.done(function(){
					$('#grid1').datagrid('reload');
				});	
			}
		});
	}

	function handleGridGroup() {
		$('#grid2').datagrid({
			url: siteURL('users/load_groups'),
			height: 320,
			rownumbers: true,
			pagination: true,
			pagePosition: 'top',
			autoRowHeight: false,
			checkbox: true,
			singleSelect: true,
			columns: [[
				{field: 'ck', checkbox: true},
				{field: 'name', title: 'Group', width: 200, sortable: true},
				{field: 'description', title: 'Description', width: 300, sortable: true}
			]]
		});

		var pager = $('#grid2').datagrid('getPager');
		pager.pagination({
			buttons: [
				{text: '<i class="icon-plus"></i> Add',  handler: addGroup},
				// {text: '<i class="icon-pencil"></i> Edit', handler: editGroup},
				{text: '<i class="icon-trash"></i> Delete', handler: deleteGroup}
			]
		});
	}

	function handleWinGroup() {
		$('#wingroup').show();
		$('#wingroup').dialog({
			modal: true,
			width: 400,
			title: 'Group Editor',
			buttons: [
				{
					text: 'Submit',
					handler: function() {
						$('#formgroup').form('submit', {
							url: siteURL('users/save_group'),
							success: function() {
								$('#wingroup').dialog('close');
								$('#grid2').datagrid('reload');
							}
						});
					}
				},
				{
					text: 'Close',
					handler: function() {
						$('#wingroup').dialog('close');
					}
				}
			]
		});

		$('#wingroup').dialog('close');

	}

	function addGroup() {
		$('#wingroup').dialog('open');
		$('#formgroup').form('clear').form('reset');
	}

	function editGroup() {
		var record = $('#grid2').datagrid('getSelected');
		if ( ! record) {
			$.messager.alert('Warning', 'No record selected', 'warning');
			return;
		}

		$('#wingroup').dialog('open');
		$('#formgroup').form('load', record);
	}

	function deleteGroup() {
		var record = $('#grid2').datagrid('getSelected');
		if ( ! record) {
			$.messager.alert('Warning', 'No record selected', 'warning');
			return;
		}

		$.messager.confirm('Confirm', 'Delete selected record?', function(r){
			if (r) {
				$.ajax({
					url: siteURL('users/delete_group'),
					type: 'post',
					dataType: 'json',
					data: record
				})
				.done(function(){
					$('#grid2').datagrid('reload');
				});	
			}
		});
	}

	function handleGridAssoc() {
		$('#grid3').datagrid({
			url: siteURL('users/load_assoc'),
			height: 320,
			rownumbers: true,
			pagination: true,
			pagePosition: 'top',
			autoRowHeight: false,
			checkbox: true,
			singleSelect: true,
			view: groupview,
			groupField: 'group_id',
			groupFormatter: function(v, rs) {
				var r = rs[0];
				return r.group_name + ' - ' + rs.length + ' Member(s)';
			},
			columns: [[
				{field: 'ck', checkbox: true},
				{field: 'username', title: 'Username', width: 200, sortable: true},
				{field: 'fullname', title: 'Fullname', width: 200, sortable: true}
			]]
		});

		var pager = $('#grid3').datagrid('getPager');
		pager.pagination({
			buttons: [
				// {text: '<i class="icon-plus"></i> Add',  handler: addAssoc},
				{text: '<i class="icon-pencil"></i> Change', handler: editAssoc}
				// {text: '<i class="icon-trash"></i> Delete', handler: deleteAssoc}
			]
		});
	}

	function handleWinAssoc() {
		$('#winassoc').show();
		$('#winassoc').dialog({
			modal: true,
			width: 400,
			title: 'Assoc Editor',
			buttons: [
				{
					text: 'Submit',
					handler: function() {
						$('#formassoc').form('submit', {
							url: siteURL('users/save_assoc'),
							success: function() {
								$('#winassoc').dialog('close');
								$('#grid3').datagrid('reload');
							}
						});
					}
				},
				{
					text: 'Close',
					handler: function() {
						$('#winassoc').dialog('close');
					}
				}
			]
		});

		$('#winassoc').dialog('close');
	}

	function addAssoc() {

	}

	function editAssoc() {
		var record = $('#grid3').datagrid('getSelected');
		if ( ! record) {
			$.messager.alert('Warning', 'No record selected', 'warning');
			return;
		}

		$('#winassoc').dialog('open');
		$('#formassoc').form('load', record);
	}

	function deleteAssoc() {

	}

	function handleTab() {

		$('#tab').on('shown.bs.tab', function(e){

			var tab = $(e.target),
				href = tab.prop('href');

			if (/#tab2/.test(href) && ! $('#grid2').data('resized')) {
				$('#grid2').datagrid('reload')
						   .data('resized', true);
			}

			if (/#tab3/.test(href) && ! $('#grid3').data('resized')) {
				$('#grid3').datagrid('reload')
						   .data('resized', true);
			}

		});

	}

	function handleSearch() {
		$('#omnisearch').on('keypress', function(e){
			if (e.keyCode === 13) {

				var query = $(this).val(),
					tab = $(' > li.active > a', $('#tab'));

				if (tab.length) {
					var m = tab.prop('href').match(/\#tab(\d)$/i),
						i = m.length && m[1],
						g = i && $('#grid'+i);
					if (g.length) g.datagrid('load', {
						query: query
					});
				}

			}
		});
	}

	return {
		init: function() {
			handleGridUser();
			handleWinUser();

			handleGridGroup();
			handleWinGroup();

			handleGridAssoc();
			handleWinAssoc();

			handleTab();
			handleSearch();
		}
	}

}(jQuery));

$(document).ready(Users.init);